#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.basic.security.oauth2.handler;

import ${package}.common.bean.vo.JsonResult;
import ${package}.common.component.service.RedisService;
import ${package}.common.emum.ReturnCodeEnum;
import ${package}.common.exception.ValidateCodeException;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Description: 登陆失败处理器
 *
 * @author wupanhua
 * @date 2019/8/6 15:28
 *
 * <pre>
 *              ${copyright}
 *      Copyright (c) 2019. All Rights Reserved.
 * </pre>
 */
@Component("authenticationFailureHandler")
@AllArgsConstructor
public class AuthenticationFailHandlerImpl implements AuthenticationFailureHandler {

    private RedisService redisService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 允许跨域
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 允许自定义请求头token(允许head跨域)
        response.setHeader("Access-Control-Allow-Headers", "token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified");
        // 设置返回头
        response.setContentType("application/json;charset=UTF-8");

        String status = "1";
        //登录失败设置请求验证码的状态
        String userName = request.getParameter("username");
        //设置过期时间为12小时
        Long expireTime = 60 * 5L;
        redisService.set(userName, status, expireTime);
        redisService.remove(request.getParameter("token"));

        // 设置验证未通过的请求头
        if (exception instanceof ValidateCodeException) {
            response.getWriter().write(JSON.toJSONString(JsonResult.getInstant(ReturnCodeEnum.VALIDATE_CODE_WRONG)));
        } else {
            // 设置验证未通过的请求头
            response.getWriter().write(JSON.toJSONString(JsonResult.getInstant(ReturnCodeEnum.LOGIN_FAIL)));
        }
    }
}
